package com.seean.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

/**
 * @authur wsx
 * @date 2020/7/8 10:38
 */
public class XmlUtil {

    private Logger log = LoggerFactory.getLogger(XmlUtil.class);

    public String createXml(String xmlStr, String fileName, String path) {
        Document doc = strToDocument(xmlStr);
        String realPath = path + fileName;
        try {
            // 判断文件是否存在，如存在就删掉它
            File file = new File(realPath);
            if (file.exists()) {
                file.delete();
            }
            if (!file.getParentFile().exists()) {
                //如果不存在则创建
                file.getParentFile().mkdirs();
            }
            /** 将document中的内容写入文件中 */
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new FileOutputStream(realPath));
            transformer.transform(source, result);
        } catch (final Exception exception) {
        }
        //返回文件保存路径
        return path + fileName;
    }

    public Document strToDocument(String xmlStr) {
        Document doc = null;
        StringReader sr = new StringReader(xmlStr);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
        } catch (ParserConfigurationException e) {
            log.info("ParserConfiguration错误:" + e);
        } catch (SAXException e) {
            log.info("SAX错误" + e);
        } catch (IOException e) {
            log.info("IO错误" + e);
        }
        return doc;
    }

    public String XmlFileToStr(String path) {
        String xmlString = "";
        byte[] strBuffer = null;
        InputStream in = null;
        int flen = 0;
        File xmlfile = new File(path);
        try {
            in = new FileInputStream(xmlfile);
            flen = (int) xmlfile.length();
            strBuffer = new byte[flen];
            in.read(strBuffer, 0, flen);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("FileNotFound错误" + e.getMessage());
        } catch (IOException e) {
            log.info("转换IO错误" + e.getMessage());
            e.printStackTrace();
        }
        xmlString = new String(strBuffer); //构建String时，可用byte[]类型，
        return xmlString;
    }
}
